/* * Copyright (C) 2021 Huawei Device Co., Ltd.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zhouyou.http.model;

import com.google.gson.Gson;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.demo.api.LoginService;
import com.zhouyou.http.demo.constant.AppConstant;
import com.zhouyou.http.demo.constant.ComParamContact;
import com.zhouyou.http.demo.model.AuthModel;
import com.zhouyou.http.demo.slice.MainAbilitySlice;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.utils.FileUtils;
import com.zhouyou.http.model.utils.MD5;
import com.zhouyou.http.model.utils.ToastUtils;
import com.zhouyou.http.request.CustomRequest;
import com.zhouyou.http.utils.HttpLog;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.aafwk.ability.delegation.IAbilityDelegator;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import org.junit.Test;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.File;

import static com.zhouyou.http.demo.constant.AppConstant.*;
import static com.zhouyou.http.demo.constant.AppConstant.XPATH1;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;

public class EasyHttpTest {

    private static IAbilityDelegator sAbilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();

    @Test
    public void getOkHttpClient() {
        OkHttpClient client = EasyHttp.getOkHttpClient();
        assertNotNull("message  is not equals", client);
    }

    @Test
    public void get() {
        EasyHttp.get(ComParamContact.Login.PATH)
                .params(ComParamContact.Login.ACCOUNT, "dddd")
                .params("userName", "AndServer")
                .sign(true)
                .timeStamp(true).execute(new CallBack<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(ApiException e) {
            }

            @Override
            public void onSuccess(String s) {
                assertTrue("onSuccess  is content ? ==", !s.isEmpty());

            }
        });
        sleep(5000);
    }

    @Test
    public void post() {

        EasyHttp.post(ComParamContact.Login.PATH)
                .params(ComParamContact.Login.ACCOUNT, "dddd")
                .params("userName", "AndServer")
                .sign(true)
                .timeStamp(true).execute(new CallBack<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(ApiException e) {
            }

            @Override
            public void onSuccess(String s) {
                assertTrue("onSuccess  is content ? ==", !s.isEmpty());

            }
        });
        sleep(5000);

    }


    @Test
    public void downLoad() {
        StringBuffer sb = new StringBuffer(SCHEMA).append(XIAOMI).append(XPATH).append(XPATH1);
        EasyHttp.downLoad(sb.toString())
                .savePath(FileUtils.getDistDir(sAbilityDelegator.getAppContext()) + "test/QQ")
                .saveName(FileUtils.getFileName(sb.toString()))
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        int progress = (int) (bytesRead * 100 / contentLength);
                        HttpLog.getInstance().e(progress + "% ");
                        assertTrue("update  更新进度大约0.表示在下载", bytesRead > 0);
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(String path) {

                    }

                    @Override
                    public void onError(ApiException e) {

                    }
                });
        sleep(5000);
    }




    @Test
    public void custom() {
        final String name = "18688994275";
        final String pass = "123456";
        final CustomRequest request = EasyHttp.custom().addConverterFactory(GsonConverterFactory.create(new Gson()))
                .sign(true)
                .timeStamp(true)
                .params(ComParamContact.Login.ACCOUNT, name)
                .params(ComParamContact.Login.PASSWORD, MD5.encrypt4login(pass, AppConstant.getAppSecret()))
                .build();

        LoginService mLoginService = request.create(LoginService.class);
        Observable<ApiResult<AuthModel>> observable = request.call(mLoginService.login(MAIN_LOGIN, request.getParams().urlParamsMap));
        Disposable disposable = observable.subscribe(new Consumer<ApiResult<AuthModel>>() {
            @Override
            public void accept(@NonNull ApiResult<AuthModel> result) throws Exception {

                assertTrue("result is null", !result.toString().isEmpty());

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                assertTrue("throwable is null", !throwable.getLocalizedMessage().isEmpty());
            }
        });
        sleep(5000);
    }



    @Test
    public void put() {
        EasyHttp.put(new StringBuffer(SCHEMA).append(YOUDUI).append(YOUDUI_API).toString())
                .removeParam("appId")
                .params("count", "4")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        assertTrue("e is null", !e.getMessage().isEmpty());
                    }

                    @Override
                    public void onSuccess(String response) {
                        assertTrue("response is null", !response.isEmpty());
                    }
                });

    }



    @Test
    public void getHttpCache() {
        EasyHttp.getInstance().setHttpCache(new Cache(new File("cache"),2048));
        Cache cache = EasyHttp.getInstance().getHttpCache();
        assertTrue("cache is null", cache!=null);
    }



    @Test
    public void getCommonHeaders() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("key", "zhangsan");
        httpParams.put("key1", "lisi");
        EasyHttp.getInstance().addCommonParams(httpParams);
        HttpParams commonParams =EasyHttp.getInstance().getCommonParams();
        String commonParamsStr=commonParams.toString();
        assertTrue("commonParams is null", !commonParamsStr.isEmpty());

    }

    @Test
    public void setBaseUrl() {
        EasyHttp.getInstance().setBaseUrl("http://www.baidu.com");
        String baseUrl=EasyHttp.getBaseUrl();
        assertEquals(baseUrl,"http://www.baidu.com");
    }

    @Test
    public void getBaseUrl() {
        String baseUrl=EasyHttp.getBaseUrl();
        assertNotNull("baseUrl  is not null", baseUrl);
    }




    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}